package com.atguigu.springcloud.config;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

@Configuration
public class GatewayConfig {
	
	@Bean
	public RouteLocator consulRouteLocator(RouteLocatorBuilder builder){
		return builder.routes()
				       .route(
				       		"payment1",//路由id
						       a ->
								       //在9527项目中的访问路径,同时该参数会拼接在uri地址后面,如果uri后有相同的地址,会替换,如果不同会继续拼接
							       a.path("/paymentall/**")
										   //uri路由的转发地址
								       .uri("lb://cloud-payment-service/payment")
										   //断言,这里采用predicate接口返回true或false,可根据自己的情况返回true或者false
										   //这里是断言在请求的参数中必须带有pass参数
								       .predicate(s -> s.getRequest().getQueryParams().getFirst("pass") != null)
										   //过滤,该处的过滤是针对该路由的,非全局
								       .filter((g,c) -> {
									       String an = g.getRequest().getQueryParams().getFirst("an");
									       if (an == null) {
										       System.out.println("没有an");
										       //响应 : 不可接受,并响应回去
										       g.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
										       return g.getResponse().setComplete();
									       }
									       //放行,c表示过滤链,将此次的过滤对象g放入c中进行放行
									       return c.filter(g);
								       })
				       )
				       .route(
						       "payment2",
						       a ->
								       a.path("/payment/port/**")
										       .uri("lb://cloud-payment-service/payment/port")
										       .predicate(s -> s.getRequest().getQueryParams().getFirst("pass") != null)
										       .filter((g,c) -> {
											       String an = g.getRequest().getQueryParams().getFirst("an");
											       if (an == null) {
												       System.out.println("没有an");
												       g.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
												       return g.getResponse().setComplete();
											       }
											       return c.filter(g);
										       })
				       )
				       .route(
						"payment3",
						a ->
								a.path("/payment/**")
										.uri("lb://cloud-payment-service/payment")
						).route(
						"payment4",
						a ->
								a.path("/guonei")
										.uri("http://news.baidu.com")
				).build();
	}
}
